import { Component, Injector } from '@angular/core';
import { AppComponentBase } from '@abp/components';
import {
  CachingServiceProxy,
  EntityDtoOfString,
  WebLogServiceProxy,
} from '@abp/service-proxies/service-proxies';
import * as _ from 'lodash';
import { FileDownloadService } from '@abp/utils/file-download.service';

@Component({
  templateUrl: './maintenance.component.html',
  styleUrls: ['./maintenance.component.less'],
})
export class MaintenanceComponent extends AppComponentBase {
  loading = false;
  caches: any = null;
  logs: any = '';

  constructor(
    injector: Injector,
    private cacheService: CachingServiceProxy,
    private webLogService: WebLogServiceProxy,
    private fileDownloadService: FileDownloadService,
  ) {
    super(injector);
  }

  ngOnInit(): void {
    this.getCaches();
    this.getWebLogs();
  }

  getCaches(): void {
    this.loading = true;
    this.cacheService.getAllCaches().subscribe(result => {
      this.caches = result.items;
      this.loading = false;
    });
  }

  clearCache(cacheName): void {
    const input = new EntityDtoOfString();
    input.id = cacheName;
    this.cacheService.clearCache(input).subscribe(() => {
      this.notify.success('清除成功！');
    });
  }

  getWebLogs(): void {
    this.webLogService.getLatestWebLogs().subscribe(result => {
      this.logs = result.latestWebLogLines;
      //this.fixWebLogsPanelHeight();
    });
  }

  getLogClass(log: string): string {
    if (log.startsWith('DEBUG')) {
      return 'label label-default';
    }

    if (log.startsWith('INFO')) {
      return 'label label-info';
    }

    if (log.startsWith('WARN')) {
      return 'label label-warning';
    }

    if (log.startsWith('ERROR')) {
      return 'label label-danger';
    }

    if (log.startsWith('FATAL')) {
      return 'label label-danger';
    }

    return '';
  }

  getLogType(log: string): string {
    if (log.startsWith('DEBUG')) {
      return 'DEBUG';
    }

    if (log.startsWith('INFO')) {
      return 'INFO';
    }

    if (log.startsWith('WARN')) {
      return 'WARN';
    }

    if (log.startsWith('ERROR')) {
      return 'ERROR';
    }

    if (log.startsWith('FATAL')) {
      return 'FATAL';
    }

    return '';
  }

  getRawLogContent(log: string): string {
    return _.escape(log)
      .replace('DEBUG', '')
      .replace('INFO', '')
      .replace('WARN', '')
      .replace('ERROR', '')
      .replace('FATAL', '');
  }

  downloadWebLogs() {
    this.webLogService.downloadWebLogs().subscribe(result => {
      this.fileDownloadService.downloadTempFile(result);
    });
  }
}
